package com.cqupt.interceptor;

import cn.hutool.core.util.StrUtil;

import com.alibaba.fastjson2.JSON;
import com.cqupt.model.constant.Constant;
import com.cqupt.model.pojo.SysUser;
import com.cqupt.model.vo.Result;
import com.cqupt.model.vo.ResultCodeEnum;
import com.cqupt.utils.AuthContextUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 获取请求方式，如果请求方式为options(预检请求)，直接放行
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            responseNoLoginInfo(response);
            return false;
        }
        String jsonUser = stringRedisTemplate.opsForValue().get(Constant.REDIS_TOKEN_KEY + token);
        if (StrUtil.isEmpty(jsonUser)) {
            responseNoLoginInfo(response);
            return false;
        }
        // 如果查到用户信息，将其存在ThreadLocal中
        SysUser sysUser = JSON.parseObject(jsonUser, SysUser.class);
        AuthContextUtil.set(sysUser);

        // 更新 redis 中 token 的过期时间
        stringRedisTemplate.expire(Constant.REDIS_TOKEN_KEY + token, Constant.DEFAULT_TOKEN_EXPIRE_TIME, TimeUnit.DAYS);

//        System.out.println("请求之前：" + AuthContextUtil.get());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除 ThreadLocal中的用户信息
        AuthContextUtil.remove();
//        System.out.println("请求之后：" + AuthContextUtil.get());
    }

    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }
}


